//@ts-nocheck
import { rpc } from '@kit.IPCKit';
import { DriverExtensionAbility } from '@kit.DriverDevelopmentKit';
import { KeyCode } from '@ohos.multimodalInput.keyCode';
import dataStorage from '@ohos.data.storage';
import { hilog } from '@kit.PerformanceAnalysisKit';
import testNapi from 'libentry.so'
import { commonEventManager } from '@kit.BasicServicesKit'
import { backgroundTaskManager } from '@kit.BackgroundTasksKit';

let defaultIndexMap : Int32Array= new Int32Array(4);

//订阅者信息
let subscriber; //用于保存创建成功的订阅者对象，后续使用其完成订阅及退订的动作
//订阅者信息
let subscribeInfo = {
    events: [commonEventManager.Support.COMMON_EVENT_SCREEN_ON, commonEventManager.Support.COMMON_EVENT_SCREEN_OFF]
};

let deviceId;

const STORAGE_KEY = [
    { key: 'key1', default: KeyCode.KEYCODE_1 },
    { key: 'key2', default: KeyCode.KEYCODE_2 }]

async function GetData() {
    hilog.info(0, 'testTag', 'GetData enter');
    try {
        await testNapi.getBoardInput()
    } catch (e) {
        hilog.info(0, 'testTag', 'get kbd input failed');
    }
}

//订阅公共事件回调
function SubscribeCB(err, data) {
    hilog.info(0, 'testTag', 'subscribe enter');
    if (err) {
        hilog.info(0, 'testTag', 'subscribe fail');
        hilog.error(0, 'testTag', `subscribe failed, code is ${err.code}, message is ${err.message}`);
        return;
    }
    hilog.info(0, 'testTag', 'subscribe OK');
    hilog.info(0, 'testTag', `subscribe ${JSON.stringify(data)}`)
    if (data == undefined || data == null) {
        hilog.info(0, 'testTag', 'data is invalid');
        return;
    }

    switch (data.event) {
        case commonEventManager.Support.COMMON_EVENT_SCREEN_ON:
            hilog.info(0, 'testTag', 'screen ON');
            testNapi.getProductDesc(deviceId);
            GetData();
            break;
        case commonEventManager.Support.COMMON_EVENT_SCREEN_OFF:
            hilog.info(0, 'testTag', 'screen OFF');
            testNapi.releaseResource();

            break;
        default:
            hilog.info(0, 'testTag', 'invalid event');
            break;
    }
}

//创建订阅者回调
function createCB(err, commonEventSubscriber) {
    if(!err) {
        hilog.info(0, 'testTag', "createSubscriber");
        subscriber = commonEventSubscriber;
        //订阅公共事件
        try {
            commonEventManager.subscribe(subscriber, SubscribeCB);
        } catch (err) {
            hilog.error(0, 'testTag', `subscribe failed, code is ${err.code}, message is ${err.message}`);
        }
    } else {
        hilog.error(0, 'testTag', `createSubscriber failed, code is ${err.code}, message is ${err.message}`);
    }
}

function PowerManagwer(){
    // 应用需要在后台保持活动状态，不被挂起。
    let request = {
        resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, // 资源类型是CPU资源，保证应用进程不被挂起
        isApply: true, // 申请资源
        timeOut: 0, // 超时时间，超过超时时间后资源自动释放
        reason: "apply", // 申请原因
        isPersist: true, // 永久持有资源
        isProcess: false, // 在应用级别申请
    };
    try {
        backgroundTaskManager.applyEfficiencyResources(request);
        hilog.info(0x0000, 'testTag', "Succeeded in invoking applyEfficiencyResources.");
    } catch (error) {
        hilog.info(0x0000, 'testTag', `Failed to invoke applyEfficiencyResources. Code is ${error.code} message is ${error.message}`);
    }
    //创建订阅者
    try {
        commonEventManager.createSubscriber(subscribeInfo, createCB);
    } catch (err) {
        hilog.error(0, 'testTag', `createSubscriber failed, code is ${err.code}, message is ${err.message}`);
    }
}

class FirstDriverAbilityStub extends rpc.RemoteObject {
    constructor(des) {
        if (typeof des === 'string') {
            super(des);
        } else {
            return null;
        }
    }
    onRemoteMessageRequest(code: number,
        data: MessageSequence,
        reply: MessageSequence,
        options: MessageOption
    ) {
        hilog.info(0, 'testTag', `testtag driver extension onRemoteMessageRequest called ${code}`);
        try{
            if (code == 1) {
                let keyIndex = data.readInt();
                let keyValue = data.readInt();
                console.info(`testtag driver extension start setOneButtonMapping key:${keyIndex} val:${keyValue}`);
                testNapi.setOneButtonMapping(keyIndex, keyValue);
                console.info(`testtag driver extension setOneButtonMapping called key:${keyIndex} val:${keyValue}`);
                reply.writeInt(keyIndex);
                return true;
            } else if (code == 3) {
                let type = data.readInt();
                hilog.info(0, 'testTag', `testtag get connection status called status:${type}`);
                reply.writeInt(type);
                return true;
            }
        } catch (error) {
            hilog.info(0, 'testTag', 'onRemoteMessageRequest exception');
        }
    }

    sendDisconnect() {
        let option = new rpc.MessageOption();
        let dataSend = new rpc.MessageSequence();
        let reply = new rpc.MessageSequence();
        hilog.info(0, 'testTag', `sendDisconnect`);
        sendMessageRequest(0x99, dataSend, reply, option).then((ret) => {
            let msg = reply.readInt();
            reply.writeInt(msg);
            hilog.info(0, 'testTag', `sendDisconnect sendMessageRequest ret:${ret} msg:${msg}`);
        }).catch((error) => {
            hilog.info(0, 'testTag', 'sendDisconnect sendMessageRequest failed');
        });
    }
}

export default class DriverExtAbility extends DriverExtensionAbility {
    getKeyMapInfo() {
        let filePath = this.context.filesDir;
        let keyStorage = dataStorage.getStorageSync(filePath + '/keyInfo');
        STORAGE_KEY.forEach((value, index) => {
            defaultIndexMap[index] = keyStorage.getSync(value.key, value.default)
        })
    }

    async onInit(want): void {
        hilog.info(0, 'testTag','DriverAbility OnInit');
        hilog.info(0, 'testTag','OnInit deviceId '+ want.parameters["deviceId"]);
        deviceId = want.parameters["deviceId"];
        let ret = testNapi.getProductDesc(want.parameters["deviceId"]);
        hilog.info(0, 'testTag','getProductDesc '+ ret);
        this.getKeyMapInfo()
        // 获取屏幕分辨率
        testNapi.setButtonMapping(defaultIndexMap);
        GetData();
    }
    onRelease() :void {
        hilog.info(0, 'testTag', 'DriverAbility onRelease');
        // 释放底层资源
        testNapi.releaseResource();
    }
    onConnect(want): rpc.RemoteObject {
        hilog.info(0, 'testTag', 'DriverAbility onConnect');
        return new FirstDriverAbilityStub('remote');
    }
    onDisconnect(want): void {
        hilog.info(0, 'testTag', 'DriverAbility onDisconnect');
        testNapi.releaseResource();
    }
    onDump(params): Array<string> {
        hilog.info(0, 'testTag', 'DriverAbility onDump, params:' + JSON.stringify(params));
        return ['params'];
    }
};